import { io } from "https://cdn.socket.io/4.8.1/socket.io.esm.min.js";

let device_info = {
    "device_id": window.browser,
    "uname": window.os,
};

let user_config = {
    "name": window.os,
    "avatar": "https://cdn.hanxiaoxin.cn/iot/esp32/http-server/images/headphoto/kanshan.png" // 默认头像
};

let device_config = {
    "topic_id": "Tiot_lonn5h6c"
}

let socket;

const sendBtn = document.getElementById("send")
const input = document.getElementById("value")

sendBtn.addEventListener("click", () => {
    const data = {
        device_info,
        user_config,
        device_config,
        msg: {
            type: "text",
            content: input.value,
            time: new Date().toLocaleString('zh-cn')
        }
    }
    console.log(data)
    socket.emit("message", data)
    input.value = ""
})

sendRequest('/api/info').then(res => {
    device_info = res["device_info"]
    user_config = res["user_config"]
    device_config = res["device_config"]
    start_chat()
}, error => {
    console.log(1)
    start_chat()
})

function start_chat() {
    const cur = document.getElementById("current");
    const uimg = document.getElementById("uimg");
    const uid = document.getElementById("uid");
    const uname = document.getElementById("uname");

    if (user_config.avatar) {
        uimg.src = user_config.avatar
    }

    if (device_info.device_id) {
        uid.innerHTML = device_info.device_id
    }

    if (user_config.name) {
        uname.innerHTML = user_config.name
    }

    socket = io("wss://www.hanxiaoxin.cn:3333");

    socket.on("connect", () => {
        console.log(socket.id);

        const currentInfo = {
            device_info,
            user_config,
            device_config
        }

        console.log(currentInfo)

        socket.emit("join", currentInfo)

        socket.emit("online", currentInfo)
    })

    socket.on("disconnect", () => {
        console.log(socket.id); // undefined
    });

    socket.on("message", (origin_data) => {
        //console.log(origin_data)
        appendMsg(origin_data);
    })

    socket.on("online", (origin_data) => {
        console.log(origin_data)

        appendOnline(origin_data);
    })
}
